package com.sso.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;

@WebFilter("/*")
public class LoginFilter implements Filter {

	private static final String _COOKIENAME = "SSO" ;
	private String ssoUrl = "http://localhost:8888/SSO/MainServlet";
    
    public LoginFilter() {

    }

	public void destroy() {

	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;
		String flag = getFlag(ssoUrl,this._COOKIENAME);
		System.out.println("--------flag:"+flag);
		String url = req.getRequestURL().toString();
		if("nologin".equals(flag)){
			res.sendRedirect(ssoUrl+"?method=login&tourl="+url);
		}else{
			request.setAttribute("user", flag);
		}
		chain.doFilter(request, response);
	}

	private String getFlag(String ssoUrl, String cookiename) {
		String url = ssoUrl+"?method=getFlag&cookiename="+cookiename;
		HttpClient hc = new HttpClient();
		GetMethod gm = new GetMethod(url);
		try {
			hc.executeMethod(gm);
			String rs = gm.getResponseBodyAsString();
			System.out.println("--------rs:"+rs);
			return rs;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}finally{
			gm.releaseConnection();
		}
		
	}

	public void init(FilterConfig fConfig) throws ServletException {
	}

}
